package middleware

import (
	"devOpsApi/config/ymlgo"
	"devOpsApi/model"
	"time"

	"github.com/dgrijalva/jwt-go"
	jwtmiddleware "github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

// execute jwt handler
func Jwt(ctx iris.Context) {
	JwtHandlerUser().Serve(ctx)
}

/**
 * 验证 jwt
 * @method JwtHandler
	token := ctx.Values().Get("jwt").(*jwt.Token)
	//userMsg :=ctx.Values().Get("jwt").(*jwt.Token).Claims.(jwt.MapClaims)
	// userMsg["id"].(float64) == 1
	// userMsg["nick_name"].(string) == iris
*/
func JwtHandlerUser() *jwtmiddleware.Middleware {

	config := ymlgo.NewConfigSysBase()
	return jwtmiddleware.New(jwtmiddleware.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(config.JwtSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		ErrorHandler: func(ctx context.Context, err error) { //错误处理
			if err == nil {
				return
			}
			ctx.StopExecution()
			ctx.StatusCode(iris.StatusOK)
			putData := make(map[string]interface{})
			putData["code"] = 50008
			putData["message"] = "接口jwt权限验证失败! : " + err.Error()
			putData["data"] = ""
			//B.crossDomain()
			ctx.JSON(putData)
		},
	})
}

/**
生成jwt token
*/
func GetUserToken(UserId string) string {
	config := ymlgo.NewConfigSysBase()
	platFormUserDb := model.NewUser()
	UserDb, _ := platFormUserDb.GetUserByUserId(UserId)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user_id": UserId,
		"Uid":     UserDb.ID,
		"iss":     "OpenPlatform",                                                      //签发人
		"iat":     time.Now().Unix(),                                                   //签发时间 nbf:生效时间 jti:编号 sub:主题 aud:受众
		"exp":     time.Now().Add(7 * 24 * 60 * time.Minute * time.Duration(1)).Unix(), //过期时间 30分钟
	})
	tokenString, _ := token.SignedString([]byte(config.JwtSecret))
	return tokenString
}
